/*
 * Reflexis is Copyright (C) 2007, by it-raum.ch
 * martin.imobersteg@it-raum.ch
 *
 * It is free software; you can redistribute it and/or modify it under the terms of either:
 * a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or
 * b) the "Artistic License".
 */

#include "ProbeReader.h"
#include "Probe.h"

#include <QtGui>
#include <QtDebug>

ProbeReader::ProbeReader(QObject *parent) : QObject(parent)
{
	port = new QextSerialPort("COM1");
	port->setBaudRate(BAUD9600);
	port->setFlowControl(FLOW_OFF);
	port->setParity(PAR_NONE);
	port->setDataBits(DATA_8);
	port->setStopBits(STOP_2);
	port->open(QIODevice::ReadWrite);
	qDebug("is open: %d", port->isOpen());

	buffer.clear();
	probe.clear();

	timer = new QTimer();
	timer->setInterval(500);

	connect(timer, SIGNAL(timeout()), this, SLOT(read()));

	start();
}

ProbeReader::~ProbeReader()
{
}

void ProbeReader::start()
{
	timer->start();
}

void ProbeReader::stop()
{
	timer->stop();
}

void ProbeReader::read()
{
	if (buffer.size() != 0 && buffer.at(0) != '|')
	{
		buffer.clear();
		qDebug() << "clear buffer";
	}
		
	int numBytes = port->bytesAvailable();

	if(numBytes > 0)
	{
		char buff[1024];
	
		qDebug("bytes available: %d", numBytes);

		if(numBytes > 1024) numBytes = 1024;

		int i = port->read(buff, numBytes);

		QChar qchar;

		for (int n=0; n < i; ++n)
		{
			qDebug("buff[%i] = hex(0x%x) = int(%d) = %c ", n, buff[n], buff[n], buff[n]);	

			qchar = QChar::fromAscii(buff[n]);

			if (qchar.isPrint())
			{
				buffer += qchar;
				qDebug() << "add n[" << n << "]: " << qchar;
			}

			// CR
			if ((int)buff[n] == 13)
			{
				buffer += "|";
			}
		}

		qDebug("received: %d", i);
		qDebug() << "buffer: " << buffer;
		qDebug() << "count: " << buffer.count("|");

		if (buffer.count("|") >= 6)
		{
			qDebug("-> go");
			
			QStringList list = buffer.split("|");
			buffer.clear();
			
			int d = list.at(1).indexOf(".");
			int t = list.at(1).indexOf(":");
			
			QString date = list.at(1).mid(d-2,8);
			QString time = list.at(1).mid(t-2,8);
			QString ident = list.at(2);
			QString result = list.at(3).trimmed();
			QString info = list.at(4).trimmed();
			QString text = list.at(5).trimmed();
			
			qDebug() << date << time << ident << result << info << text;
			
			Probe probe;
			probe.setDate(date);
			probe.setTime(time);
			probe.setIdent(ident);
			probe.setResult(result);
			probe.setInfo(info);
			probe.setText(text);

			emit probeReady(probe);
		}
	}
}

bool ProbeReader::checkBCC()
{
	return true;
}

